<template>
  <view class="page">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="navbar-content">
        <view class="left-section" @tap="goBack">
          <image
            src="/static/icons/left_arrow.png"
            class="back-icon"
            mode="aspectFit"
          ></image>
        </view>
        <text class="navbar-title">编辑基本信息</text>
        <text class="save-btn" @tap="saveProfile">保存</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="content" scroll-y>
      <!-- 基本信息 -->
      <view class="section">
        <uni-list>
          <!-- 称谓 -->
          <uni-list-item>
            <template v-slot:header>
              <text class="label">称谓</text>
            </template>
            <template v-slot:body>
              <picker
                :range="sexOptions"
                :range-key="'label'"
                @change="onSexChange"
                class="picker"
              >
                <view class="picker-content">
                  <text :class="['value', formData.sex ? '' : 'placeholder']">
                    {{ sexText || "暂未设置" }}
                  </text>
                  <image
                    src="/static/icons/right-arrow.png"
                    class="arrow-icon"
                  ></image>
                </view>
              </picker>
            </template>
          </uni-list-item>

          <!-- 真实姓名 -->
          <uni-list-item>
            <template v-slot:header>
              <text class="label">真实姓名</text>
            </template>
            <template v-slot:body>
              <view class="real-name-wrapper">
                <text class="real-name-text">{{ formData.realName || '暂未设置' }}</text>
                <text class="real-name-tip">姓名与入驻企业时填写的一致，更改需要解绑企业重新入驻</text>
              </view>
            </template>
          </uni-list-item>

          <!-- 昵称 -->
          <uni-list-item @click="showNicknamePopup" clickable  > 
            <template v-slot:header>
              <text class="label">昵称</text>
            </template>
            <template v-slot:body>
              <view class="item-content">
                <text :class="['value', formData.nickName ? '' : 'placeholder']">
                  {{ formData.nickName || "暂未设置" }}
                </text>
                <image
                  src="/static/icons/right-arrow.png"
                  class="arrow-icon"
                ></image>
              </view>
            </template>
          </uni-list-item>

          <!-- 邮箱 -->
          <uni-list-item @click="showEmailPopup" clickable>
            <template v-slot:header>
              <text class="label">邮箱</text>
            </template>
            <template v-slot:body>
              <view class="item-content">
                <text :class="['value', formData.email ? '' : 'placeholder']">
                  {{ formData.email || "暂未设置" }}
                </text>
                <image
                  src="/static/icons/right-arrow.png"
                  class="arrow-icon"
                ></image>
              </view>
            </template>
          </uni-list-item>

          <!-- 参加工作时间 -->
          <uni-list-item>
            <template v-slot:header>
              <text class="label">参加工作时间</text>
            </template>
            <template v-slot:body>
              <picker mode="date" @change="onWorkDateChange" class="picker">
                <view class="picker-content">
                  <text
                    :class="['value', formData.startWorkDate ? '' : 'placeholder']"
                  >
                    {{ formData.startWorkDate || "暂未设置" }}
                  </text>
                  <image
                    src="/static/icons/right-arrow.png"
                    class="arrow-icon"
                  ></image>
                </view>
              </picker>
            </template>
          </uni-list-item>
        </uni-list>
      </view>
    </scroll-view>

    <!-- 昵称输入弹窗 -->
    <uni-popup ref="nicknamePopupRef" type="bottom">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">编辑昵称</text>
          <text class="popup-close" @click="closeNicknamePopup">取消</text>
        </view>
        <view class="popup-body">
          <input
            v-model="tempNickname"
            placeholder="请输入昵称"
            class="popup-input"
            maxlength="20"
            focus
          />
        </view>
        <view class="popup-footer">
          <button class="popup-btn confirm-btn" @click="confirmNickname">确定</button>
        </view>
      </view>
    </uni-popup>

    <!-- 邮箱输入弹窗 -->
    <uni-popup ref="emailPopupRef" type="bottom">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">编辑邮箱</text>
          <text class="popup-close" @click="closeEmailPopup">取消</text>
        </view>
        <view class="popup-body">
          <input
            v-model="tempEmail"
            placeholder="请输入邮箱地址"
            class="popup-input"
            type="email"
            focus
          />
        </view>
        <view class="popup-footer">
          <button class="popup-btn confirm-btn" @click="confirmEmail">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from "vue";
import { useUserStore } from "@/stores/modules/user";
import { modifyUserInfoApi, getHrInfoApi } from "@/api/user";

const userStore = useUserStore();

// 弹窗引用
const nicknamePopupRef = ref();
const emailPopupRef = ref();

// 临时数据
const tempNickname = ref("");
const tempEmail = ref("");

// 性别选项
const sexOptions = [
  { value: 1, label: "男" },
  { value: 2, label: "女" },
  { value: 3, label: "保密" },
];

// 表单数据
const formData = ref({
  sex: 3,
  realName: "",
  nickName: "",
  email: "",
  startWorkDate: "",
});

// 计算属性：性别文本
const sexText = computed(() => {
  const sexOption = sexOptions.find(
    (item) => item.value === formData.value.sex
  );
  return sexOption ? sexOption.label : "";
});

// 初始化数据
const initFormData = async () => {
  try {
    // 调用getHrInfoApi获取最新的HR信息
    const hrInfo = await getHrInfoApi();
    console.log('获取到的HR信息:', hrInfo);
    
    if (hrInfo) {
      formData.value = {
        sex: hrInfo.sex || 3,
        realName: hrInfo.realName || "",
        nickName: hrInfo.nickName || hrInfo.nickname || "",
        email: hrInfo.email || "",
        startWorkDate: hrInfo.startWorkDate || "",
      };
    }
  } catch (error) {
    console.error('获取HR信息失败:', error);
    // 如果API调用失败，回退到使用store中的数据
    const userInfo = userStore.userInfo;
    if (userInfo) {
      formData.value = {
        sex: userInfo.sex || 3,
        realName: userInfo.realName || "",
        nickName: userInfo.nickName || userInfo.nickname || "",
        email: userInfo.email || "",
        startWorkDate: userInfo.startWorkDate || "",
      };
    }
  }
};

// 事件处理
const onSexChange = (e) => {
  const index = parseInt(e.detail.value);
  formData.value.sex = sexOptions[index].value;
};

const onWorkDateChange = (e) => {
  formData.value.startWorkDate = e.detail.value;
};

// 昵称弹窗相关
const showNicknamePopup = () => {
  tempNickname.value = formData.value.nickName;
  
  if (nicknamePopupRef.value) {
    try {
      nicknamePopupRef.value.open();
    } catch (error) {
      console.error('昵称弹窗打开失败:', error);
    }
  }
};

const closeNicknamePopup = () => {
  if (nicknamePopupRef.value) {
    nicknamePopupRef.value.close();
  }
};

const confirmNickname = () => {
  formData.value.nickName = tempNickname.value;
  closeNicknamePopup();
};

// 邮箱弹窗相关
const showEmailPopup = () => {
  tempEmail.value = formData.value.email;
  
  if (emailPopupRef.value) {
    try {
      emailPopupRef.value.open();
    } catch (error) {
      console.error('邮箱弹窗打开失败:', error);
    }
  }
};

const closeEmailPopup = () => {
  if (emailPopupRef.value) {
    emailPopupRef.value.close();
  }
};

const confirmEmail = () => {
  formData.value.email = tempEmail.value;
  closeEmailPopup();
};

const goBack = () => {
  uni.navigateBack();
};

const formatDate = (dateStr) => {
  if (!dateStr) return "";
  return dateStr;
};

const saveProfile = async () => {
  try {
    uni.showLoading({
      title: "保存中...",
      mask: true,
    });

    // 构建提交数据
    const submitData = {
      userId: userStore.userInfo.id,
      sex: formData.value.sex,
      nickName: formData.value.nickName,
      email: formData.value.email,
      startWorkDate: formatDate(formData.value.startWorkDate),
    };

    // 调用API保存用户信息
    await modifyUserInfoApi(submitData);

    // 更新本地存储
    await userStore.getUserInfoAction();
    uni.hideLoading();
    uni.showToast({
      title: "保存成功",
      icon: "success",
    });
    
    // 通过具体路径跳转回editProfile页面
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/company/hrEdit/editProfile'
      });
    }, 1500);
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || "保存失败，请重试",
      icon: "none",
    });
  }
};

onMounted(async () => {
  await initFormData();
});
</script>

<style scoped>
.page {
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 导航栏 */
.navbar {
  background-color: #fff;
  border-bottom: 1rpx solid #e6e6e6;
  /* 适配安全区域 */
  padding-top: var(--status-bar-height);
}

.navbar-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  height: 88rpx;
  position: relative;
}

.left-section {
  display: flex;
  align-items: center;
  min-width: 80rpx;
  padding: 20rpx 0;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.save-btn {
  font-size: 32rpx;
  color: #00bdb4;
  z-index: 10;
  min-width: 80rpx;
  text-align: right;
}

/* 内容区域 */
.content {
  flex: 1;
  padding: 20rpx 0;
}

.section {
  background-color: #fff;
  margin-bottom: 20rpx;
}

.label {
  font-size: 32rpx;
  color: #333;
}

.item-content {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex: 1;
}

.picker {
  flex: 1;
}

.picker-content {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.value {
  font-size: 32rpx;
  color: #333;
}

.placeholder {
  color: #999;
}

.arrow-icon {
  width: 24rpx;
  height: 24rpx;
  margin-left: 10rpx;
}

.real-name-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  flex: 1;
}

.real-name-text {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 8rpx;
}

.real-name-tip {
  font-size: 24rpx;
  color: #999;
  text-align: right;
  line-height: 1.4;
}

/* 弹窗样式 */
.popup-content {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 0;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

.popup-close {
  font-size: 32rpx;
  color: #999;
}

.popup-body {
  padding: 30rpx;
}

.popup-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #e6e6e6;
  border-radius: 12rpx;
  padding: 0 20rpx;
  font-size: 32rpx;
  color: #333;
  background-color: #f8f8f8;
}

.popup-footer {
  padding: 0 30rpx 30rpx;
}

.popup-btn {
  width: 100%;
  height: 80rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  border: none;
}

.confirm-btn {
  background-color: #00bdb4;
  color: #fff;
}

.confirm-btn:active {
  background-color: #009a92;
}

/* 调整uni-list字体大小和间距 */
:deep(.uni-list-item__container) {
  padding: 50rpx 15rpx !important;
}
</style>